{
 "cells": [
  {
   "cell_type": "code",
   "id": "initial_id",
   "metadata": {
    "collapsed": true,
    "ExecuteTime": {
     "end_time": "2025-04-08T19:09:05.585804Z",
     "start_time": "2025-04-08T19:09:05.575060Z"
    }
   },
   "source": [
    "import os\n",
    "os.chdir('/Users/Ireneee-/Desktop/st456/gp')  # macOS/Linux"
   ],
   "outputs": [],
   "execution_count": 10
  },
  {
   "metadata": {
    "ExecuteTime": {
     "end_time": "2025-04-08T19:09:33.871673Z",
     "start_time": "2025-04-08T19:09:05.608745Z"
    }
   },
   "cell_type": "code",
   "source": [
    "import os\n",
    "import pandas as pd\n",
    "import numpy as np\n",
    "from PIL import Image\n",
    "\n",
    "# Load the dataset\n",
    "df = pd.read_csv('fer2013.csv')\n",
    "\n",
    "# Base output directory\n",
    "base_dir = 'fer2013'\n",
    "\n",
    "# Create folders if they don't exist\n",
    "for usage in df['Usage'].unique():\n",
    "    usage_path = os.path.join(base_dir, usage)\n",
    "    os.makedirs(usage_path, exist_ok=True)\n",
    "\n",
    "# Convert pixels to image and save\n",
    "for idx, row in df.iterrows():\n",
    "    pixels = list(map(int, row['pixels'].split()))\n",
    "    image_array = np.array(pixels).reshape(48, 48).astype(np.uint8)\n",
    "    image = Image.fromarray(image_array)\n",
    "\n",
    "    usage = row['Usage']\n",
    "    filename = f\"{idx}.png\"\n",
    "    filepath = os.path.join(base_dir, usage, filename)\n",
    "    image.save(filepath)\n",
    "\n",
    "print(\"Conversion complete. Images saved in fer2013/[Usage]/ folders.\")\n"
   ],
   "id": "5dee5500116d5831",
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Conversion complete. Images saved in fer2013/[Usage]/ folders.\n"
     ]
    }
   ],
   "execution_count": 11
  },
  {
   "metadata": {
    "ExecuteTime": {
     "end_time": "2025-04-08T19:09:50.585586Z",
     "start_time": "2025-04-08T19:09:33.948449Z"
    }
   },
   "cell_type": "code",
   "source": [
    "import os\n",
    "import shutil\n",
    "import pandas as pd\n",
    "\n",
    "# Base path\n",
    "base_dir = 'fer2013'\n",
    "csv_file = 'fer2013new.csv'\n",
    "\n",
    "# Emotion labels\n",
    "emotion_labels = [\n",
    "    'neutral', 'happiness', 'surprise', 'sadness',\n",
    "    'anger', 'disgust', 'fear', 'contempt', 'unknown'\n",
    "]\n",
    "\n",
    "# Load new CSV\n",
    "df = pd.read_csv(csv_file)\n",
    "\n",
    "# Create subdirectories for each usage and emotion\n",
    "for usage in df['Usage'].unique():\n",
    "    if pd.isna(usage): continue\n",
    "    for emotion in emotion_labels:\n",
    "        os.makedirs(os.path.join(base_dir, usage, emotion), exist_ok=True)\n",
    "\n",
    "# Track moved files\n",
    "moved_files = set()\n",
    "\n",
    "# Process each row\n",
    "for _, row in df.iterrows():\n",
    "    usage = row['Usage']\n",
    "    image_name = row['Image name']\n",
    "\n",
    "    if pd.isna(image_name) or row['NF'] == 10:\n",
    "        continue\n",
    "\n",
    "    # Convert image name like 'fer0000003.png' to '3.png'\n",
    "    try:\n",
    "        index = int(image_name.replace('fer', '').replace('.png', ''))\n",
    "        actual_image_name = f\"{index}.png\"\n",
    "    except:\n",
    "        continue\n",
    "\n",
    "    # Determine dominant emotion\n",
    "    emotion_counts = row[emotion_labels].values\n",
    "    if sum(emotion_counts) == 0:\n",
    "        continue\n",
    "\n",
    "    dominant_emotion = emotion_labels[emotion_counts.argmax()]\n",
    "\n",
    "    src_path = os.path.join(base_dir, usage, actual_image_name)\n",
    "    dst_path = os.path.join(base_dir, usage, dominant_emotion, actual_image_name)\n",
    "\n",
    "    if os.path.exists(src_path):\n",
    "        shutil.move(src_path, dst_path)\n",
    "        moved_files.add((usage, actual_image_name))\n",
    "\n",
    "# Delete leftover images not moved\n",
    "for usage in ['Training', 'PrivateTest', 'PublicTest']:\n",
    "    usage_path = os.path.join(base_dir, usage)\n",
    "    if not os.path.exists(usage_path):\n",
    "        continue\n",
    "\n",
    "    for file in os.listdir(usage_path):\n",
    "        file_path = os.path.join(usage_path, file)\n",
    "        if os.path.isfile(file_path) and (usage, file) not in moved_files:\n",
    "            os.remove(file_path)\n",
    "\n",
    "print(\"✅ Done: Images sorted by emotion. Unlabeled files deleted.\")\n"
   ],
   "id": "df4c989564b9465a",
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "✅ Done: Images sorted by emotion. Unlabeled files deleted.\n"
     ]
    }
   ],
   "execution_count": 12
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 2
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython2",
   "version": "2.7.6"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
